const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const collection = db.collection("activity-participants");

module.exports = {
  /**
   * 获取用户已参加的活动列表
   * @param {string} user_id 用户ID
   * @returns {Promise<object>} 活动列表
   */
  async getParticipatedActivities(user_id) {
    try {
      // 查询用户参与的活动记录
      const res = await collection
        .aggregate()
        .match({
          user_id,
        })
        .lookup({
          from: "news-articles-image", // 活动表格
          let: {
            images_id: "$activity_id", // $activity_id是主表记录的副表ID
          },
          pipeline: $.pipeline()
            .match(
              dbCmd.expr(
                $.and([
                  $.eq(["$_id", "$$images_id"]), // 主表记录的ID等于副表记录的ID
                  // $.eq(["$article_status", 1]), // $article_status等于1表示已发布，这是副表的字段
                ])
              )
            )
            .project({
              _id: 0,
              content: 1,
              title: 1,
              start_time: 1,
              end_time: 1,
              region_address: 1,
              location_name: 1,
              article_status: 1,
            })
            .done(),
          as: "activity_info",
        })
        .sort({
          join_time: -1,
        })
        .end();

      return {
        code: 0,
        message: "查询成功",
        data: res.data,
      };
    } catch (err) {
      return {
        code: -1,
        message: err.message || "查询失败",
        data: null,
      };
    }
  },
  /**
   * 检查用户是否已参加活动
   * @param {string} activity_id 活动ID
   * @param {string} user_id 用户ID
   * @returns {Promise<object>} 检查结果
   */
  async checkParticipated(activity_id, user_id) {
    try {
      const res = await db
        .collection("activity-participants")
        .where({
          activity_id,
          user_id,
        })
        .get();

      return {
        code: 0,
        message: "查询成功",
        data: res.data.length > 0,
      };
    } catch (err) {
      return {
        code: -1,
        message: err.message || "查询失败",
        data: null,
      };
    }
  },
  /**
   * 参加活动
   * @param {string} activity_id 活动ID
   * @param {string} user_id 用户ID
   * @returns {Promise<object>} 参加结果
   */
  async joinActivity(activity_id, user_id) {
    try {
      // 检查活动是否存在
      const activityRes = await db
        .collection("news-articles-image")
        .doc(activity_id)
        .get();
      if (!activityRes.data || activityRes.data.length === 0) {
        throw new Error("活动不存在");
      }

      // 记录参与信息
      const res = await db.collection("activity-participants").add({
        activity_id,
        user_id,
        join_time: Date.now(),
      });

      return {
        code: 0,
        message: "参加成功",
        data: res,
      };
    } catch (err) {
      return {
        code: -1,
        message: err.message || "参加失败",
        data: null,
      };
    }
  },
};
